<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="45%"
      v-dialogDrag
      append-to-body
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        v-loading="formLoading"
        label-width="140px"
      >
        <el-form-item label="活动标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入活动标题" />
        </el-form-item>
        <el-form-item label="活动地址" prop="address">
          <el-input v-model="formData.address" placeholder="请输入活动地址" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select
            v-model="formData.category"
            placeholder="请选择分类"
            clearable
            size="small"
          >
            <el-option
              v-for="dict in statusoptions"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="活动文章">
          <Editor v-model="formData.content" :min-height="192" />
        </el-form-item>
        <el-form-item label="活动封面" prop="cover">
          <el-upload
            :action="actionUrl"
            :headers="headers"
            :show-file-list="false"
            class="avatar-uploader"
            :before-upload="beforeImageUpload"
            :on-success="handleUploadSuccess"
          >
            <img v-if="formData.cover" :src="formData.cover" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">
              支持 bmp/png/jpeg/jpg/gif 格式，大小不超过 2M
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="活动二维码" prop="qrCode">
          <el-upload
            :action="actionUrl"
            :headers="headers"
            :show-file-list="false"
            class="avatar-uploader"
            :before-upload="beforeImageUpload"
            :on-success="qrCodeSuccess"
          >
            <img v-if="formData.qrCode" :src="formData.qrCode" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">
              支持 bmp/png/jpeg/jpg/gif 格式，大小不超过 2M
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="活动开始时间" prop="startTime">
          <el-date-picker
            v-model="activityDate"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="onSelectDateTimeChanged"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading"
          >确 定</el-button
        >
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as ActivityApi from "@/api/ai/activity";
import Editor from "@/components/Editor";
import { getAccessToken } from "@/utils/auth";
import { DICT_TYPE, getDictDatas } from "@/utils/dict";
export default {
  name: "ActivityForm",
  components: {
    Editor,
  },
  data() {
    return {
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      statusoptions: getDictDatas(DICT_TYPE.Activity_Status),
      activityDate:[],
      imageUrl: "",
      qrCodeimageUrl:'',
      // 表单参数
      formData: {
        id: undefined,
        title: undefined,
        address: undefined,
        content: undefined,
        cover: undefined,
        category: undefined,
        qrCode: undefined,
        startTime: undefined,
        endTime: undefined,
        reviewStatus: undefined,
      },
      headers: { Authorization: "Bearer " + getAccessToken() }, // 设置上传的请求头部
      actionUrl: process.env.VUE_APP_BASE_API + "/admin-api/infra/file/upload",
      // 表单校验
      formRules: {
        title: [
          { required: true, message: "活动标题不能为空", trigger: "blur" },
        ],
        address: [
          { required: true, message: "活动地址不能为空", trigger: "blur" },
        ],
        content: [
          { required: true, message: "活动文章不能为空", trigger: "blur" },
        ],
        category: [
          { required: true, message: "分类不能为空", trigger: "blur" },
        ],
        cover: [
          { required: true, message: "活动封面不能为空", trigger: "blur" },
        ],
        startTime: [
          { required: true, message: "活动时间不能为空", trigger: "blur" },
        ],
      
      },
    };
  },
  methods: {
    onSelectDateTimeChanged(val) {
      console.log("选择时间改变", val, this.activityDate);
      this.formData.startTime = this.formatDate(val[0]);
      this.formData.endTime = this.formatDate(val[1]);
      console.log("选择时间改变this.formData",  this.formData.startTime);
    },
     formatDate(dateString) {
  // 将日期字符串转换为Date对象
  const date = new Date(dateString);

  // 组合年月日时分
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, '0'); // getMonth返回0-11，需要加1
  const day = date.getDate().toString().padStart(2, '0');
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  const seconds = date.getSeconds().toString().padStart(2, '0');
  // 构建并返回新格式的日期时间字符串
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
},
    handleUploadSuccess(res) {
      console.log("resxxxx", res);
      this.formData.cover = res.data;
    },
    qrCodeSuccess(res){
      console.log("resxxxx", res);
      this.formData.qrCode = res.data;
    },
    beforeImageUpload(file) {
      // 校验格式
      const isType =
        file.type === "image/jpeg" ||
        file.type === "image/png" ||
        file.type === "image/gif" ||
        file.type === "image/bmp" ||
        file.type === "image/jpg";
      if (!isType) {
        this.$message.error("上传图片格式不对!");
        return false;
      }
      // 校验大小
      const isLt = file.size / 1024 / 1024 < 2;
      if (!isLt) {
        this.$message.error("上传图片大小不能超过 2M!");
        return false;
      }
      return true;
    },
    /** 打开弹窗 */
    async open(id) {
      this.dialogVisible = true;

      this.reset();
      // 修改时，设置数据
      if (id) {
        this.formLoading = true;
        try {
          const res = await ActivityApi.getActivity(id);
          this.formData = res.data;
          this.activityDate=[res.data.startTime, res.data.endTime]
          this.title = "修改线下活动";
        } finally {
          this.formLoading = false;
        }
      }else{
        this.title = "新增线下活动";
      }
    
    },
    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
       
        const data = this.formData;
        // 修改的提交
        if (data.id) {
          await ActivityApi.updateActivity(data);
          this.$modal.msgSuccess("修改成功");
          this.dialogVisible = false;
          this.$emit("success");
          return;
        }
        // 添加的提交
        await ActivityApi.createActivity(data);
        this.$modal.msgSuccess("新增成功");
        this.dialogVisible = false;
        this.$emit("success");
      } finally {
        this.formLoading = false;
      }
    },
    /** 表单重置 */
    reset() {
      this.activityDate=[];
      this.formData = {
        id: undefined,
        title: undefined,
        address: undefined,
        content: undefined,
        cover: undefined,
        category: undefined,
        qrCode: undefined,
        startTime: undefined,
        endTime: undefined,
        reviewStatus: undefined,
      };
      this.resetForm("formRef");
    },
  },
};
</script>
<style lang="scss" scoped>
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar-uploader :deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
